package com.ewzj.bigdata.mvp.presenter

import android.app.Application
import android.content.Intent
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import com.ewzj.bigdata.app.config.AppKey
import com.ewzj.bigdata.app.utils.Apputils
import com.ewzj.bigdata.app.utils.RxUtils
import com.ewzj.bigdata.mvp.contract.HourseWebActivityContract
import com.ewzj.bigdata.mvp.model.bean.HrefBean
import com.ewzj.bigdata.mvp.model.bean.JsCommentbean
import com.ewzj.bigdata.mvp.model.bean.JsReplayBean
import com.ewzj.bigdata.mvp.model.bean.JsReqcommentBean
import com.ewzj.bigdata.mvp.model.reqbean.ReqPraise
import com.ewzj.bigdata.mvp.model.reqbean.Reqcomentbean
import com.ewzj.bigdata.mvp.model.rspbean.BaseData
import com.ewzj.bigdata.mvp.model.rspbean.CommentBean
import com.ewzj.bigdata.mvp.model.rspbean.HomeBean
import com.ewzj.bigdata.mvp.model.rspbean.InfoBean
import com.ewzj.bigdata.mvp.ui.activity.LoginActivity
import com.ewzj.bigdata.mvp.ui.view.ObservableWebView
import com.github.lzyzsd.jsbridge.BridgeWebView
import com.github.lzyzsd.jsbridge.CallBackFunction
import com.google.gson.Gson
import com.jess.arms.mvp.BasePresenter
import com.jess.arms.utils.DataHelper
import com.jess.arms.utils.UiUtils
import com.umeng.socialize.ShareAction
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import me.jessyan.rxerrorhandler.core.RxErrorHandler
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject

/**
 * author:zhangjing
 * 作用:
 * return:
 */
class HourseWebActivityPresenter @Inject constructor(val mGson: Gson, val mErrorHandler: RxErrorHandler, val application: Application, view: HourseWebActivityContract.View, model: HourseWebActivityContract.Model) : BasePresenter<HourseWebActivityContract.Model, HourseWebActivityContract.View>(model, view) {
    lateinit var callBackFunction: CallBackFunction
    lateinit var webview: ObservableWebView
    val context = mRootView as AppCompatActivity
    var replayBean: JsReplayBean? = null
    val apiToken by lazy { DataHelper.getStringSF(context, AppKey.API_TOKEN) }
    //    回复还是评论
    var commentType: Int = 1

    fun addScanRecord(url: String) {
        mModel.read(url).compose(RxUtils.applySchedulers(mRootView)).subscribe(object : ErrorHandleSubscriber<BaseData<Any>>(mErrorHandler) {
            override fun onNext(t: BaseData<Any>?) {

            }
        })
    }
    fun initBridgeWebview(bridgewebview: ObservableWebView, url: String) {
        this.webview=bridgewebview
        webview.registerHandler("linkOther") { data, function -> linkOther(data, function) }
        webview.registerHandler("zanTalk") { data, function -> zanTalk(data, function) }
        webview.registerHandler("open_on_side") { data, function -> open_on_side(data) }
        webview.registerHandler("talkTalk") { data, function ->
            callBackFunction = function
            talkTalk(data)
        }
        if (!apiToken.isNullOrEmpty()) {
            val extraHeaders = HashMap<String, String>()
            extraHeaders.put("token", apiToken)
            webview.loadUrl(url, extraHeaders)
        } else {
            webview.loadUrl(url)
        }
    }

    /*
    *
    * webview 与本地交互相关函数
    * */
    private fun open_on_side(json: String?) {
        val hrefBean = mGson.fromJson(json, HrefBean::class.java)
        if (hrefBean != null) {
            if (hrefBean!!.getHref().contains("tel")) {
                val uri = Uri.parse(hrefBean!!.getHref())
                val intent = Intent()
                intent.action = Intent.ACTION_CALL
                intent.data = uri
                context.startActivity(intent)
            } else {
                UiUtils.SnackbarText("关闭webview")
            }

        }
    }

    private fun linkOther(json: String, function: CallBackFunction) {
        Observable.just(json).map { t -> mGson.fromJson(t, HomeBean::class.java) }.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : ErrorHandleSubscriber<HomeBean>(mErrorHandler) {
                    override fun onNext(databean: HomeBean) {
                        mRootView.reloadUrl(databean.go_url)
                        mRootView.reSetTitle(databean.name)
                        mRootView.isCollected(databean.is_collect)
                        function.onCallBack("点击推荐房源")
                    }
                })

    }


    //评论处点赞 评论处点赞zanTalk
    fun zanTalk(json: String, function: CallBackFunction) {
        if (!Apputils.Utils.checkIsLogin(context)) {
            LoginActivity.startLoginActivity(context)
        }
        Observable.just(json).debounce(200, TimeUnit.MICROSECONDS).map { t -> mGson.fromJson(t, JsCommentbean::class.java) }
                .map { t -> ReqPraise(t.groupId, t.id, 1) }
                .flatMap { t -> mModel.doPraise(t) }
                .compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object : ErrorHandleSubscriber<BaseData<String>>(mErrorHandler) {
                    override fun onNext(t: BaseData<String>?) {
                        function.onCallBack(json)
                    }

                })
    }

    fun talkTalk(json: String) {
        if (!Apputils.Utils.checkIsLogin(context)) {
            LoginActivity.startLoginActivity(context)
        }
        replayBean = mGson.fromJson(json, JsReplayBean::class.java)
        commentType = 2
    }


    fun doComment(content: String, homeBean: HomeBean) {
        if (content.isNullOrEmpty()) {
            when (commentType) {
                1 -> UiUtils.SnackbarText("评论内容不能为空哟～")
                2 -> UiUtils.SnackbarText("回复内容不能为空哟～")
            }
            return
        }
        Observable.just(content).map { t ->
            val reqcomment = Reqcomentbean()
            kotlin.run {
                reqcomment.setContent(content)
                if (commentType == 1) {
                    reqcomment.setList_id(homeBean.id)
                    reqcomment.setTable_id(homeBean.groupId)
                } else {
                    reqcomment.setList_id(replayBean!!.getId())
                    reqcomment.setTable_id(replayBean!!.getGroupId())
                    reqcomment.setId(replayBean!!.getTalkId())
                }
            }
            reqcomment
        }.flatMap { t -> mModel.docomment(t) }
                .compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object :ErrorHandleSubscriber<BaseData<CommentBean>>(mErrorHandler){
                    override fun onNext(t: BaseData<CommentBean>) {
                        mRootView.reSethint("请输入你的评论")
                        if (commentType==1){
                            UiUtils.SnackbarText("评论成功")
                            webview.callHandler("refreshConment", mGson.toJson(t.data), CallBackFunction { data -> UiUtils.SnackbarText(data) })
                        }else{
                            val jsReplayBean = JsReqcommentBean()
                            jsReplayBean.nickname = t.data!!.getNickname()
                            jsReplayBean.setReply(t.data!!.getContent())
                            jsReplayBean.setTalkId(replayBean!!.getTalkId().toString() + "")
                            jsReplayBean.setGroupId(replayBean!!.getGroupId().toString() + "")
                            jsReplayBean.setListId(replayBean!!.getId().toString() + "")
                            jsReplayBean.setTishi(replayBean!!.getTishi())
                            UiUtils.SnackbarText("回复成功")
                            val json = mGson.toJson(jsReplayBean)
                            callBackFunction.onCallBack(json)
                        }
                        commentType=1
                    }

                })
    }

    fun ShareWeb(infodata: HomeBean, share: SHARE_MEDIA) {
//        UiUtils.SnackbarText("tinker效果测试")
        val web = UMWeb(infodata.three_url)
        if (!infodata.thumb.isNullOrEmpty()){
            val thumb = UMImage(context, infodata.thumb)
            web.setThumb(thumb)
        }
        web.description = infodata.sources
        web.title = infodata.name
        ShareAction(context).withMedia(web).setPlatform(share).setCallback(AppKey.umShareListener).share()
    }
}